import json
import datetime
from collections import OrderedDict

def get_check_data(data):
    item = OrderedDict(
        time=datetime.datetime.now().strftime('%Y-%m-%d %H:%M:%S'),
        summary=OrderedDict(ok=0, bad=0, critical=0, error=0, total=0),
        ok_item=OrderedDict(),
        bad_item=OrderedDict(),
        critical_item=OrderedDict(),
        error_item=OrderedDict()
    )
    for host, host_data in data.items():
        result = host_data.get('check_result', {})
        if 'msg' in result:
            item['error_item'][host] = {'msg': result['msg']}
            continue

        try:
            info = json.loads(result.get('stdout', '{}'), object_pairs_hook=OrderedDict)
            if info.get('critical'):
                item['critical_item'][host] = info
            elif info.get('bad'):
                item['bad_item'][host] = info
            else:
                item['ok_item'][host] = info
        except json.JSONDecodeError:
            item['error_item'][host] = {'msg': 'Invalid JSON data'}

    # 统计总数
    item['summary']['ok'] = len(item['ok_item'])
    item['summary']['bad'] = len(item['bad_item'])
    item['summary']['critical'] = len(item['critical_item'])
    item['summary']['error'] = len(item['error_item'])
    item['summary']['total'] = sum(item['summary'].values())

    return item

class FilterModule:
    def filters(self):
        return {'get_check_data': get_check_data}


